<?php
//文件上传
use Think\Cache;

function saveFile($savePath)
{
    //如果目录不存在，创建目录
    if (!file_exists(DOC_ROOT . '/Public/upload/' . $savePath . '/')) {
        mkdir(DOC_ROOT . '/Public/upload/' . $savePath . '/');
    }

    $config = array(
        //'maxSize'    =>    3145728,
        'rootPath' => DOC_ROOT . '/Public/upload/',
        'savePath' => '/' . $savePath . '/',
        'saveName' => array('uniqid', ''),
        'exts' => array('jpg', 'gif', 'png', 'jpeg'),
        'autoSub' => false,
        'subName' => array('date', 'Ymd'),
    );
    $upload = new \Think\Upload($config);// 实例化上传类

    // 上传文件
    $info = $upload->upload();
    if (!$info) {// 上传错误提示错误信息
        echo $upload->getError();
    } else {// 上传成功
        echo json_encode($info['file']);
    }
}

//获取 redis 实例
function getRedisHandler()
{
    return Cache::getInstance("redis");
}

//清除redis中key为$key的缓存数据
function clearCachedObjectFor($key)
{
    getRedisHandler()->rm($key);
}

//将$obj保存到redis中,key为$key
function store($key, $obj)
{
    getRedisHandler()->set($key, $obj);
}


/**
 * redis缓存
 * @param $key redis中的key
 * @param $cachedNotFoundHandler 缓存不存在时执行该handler
 * @return string
 */
function searchCacheBeforeDB($key, $cachedNotFoundHandler)
{
    if (!is_callable($cachedNotFoundHandler)) {
        return "handler参数异常.";
    }

    try {
        $cache = getRedisHandler();
        $objects = $cache->get($key);
        if (!$objects) {
            $objects = $cachedNotFoundHandler();
            $cache->set($key, $objects);
        }
    } catch (\Think\Exception $e) {
        $objects = "handler参数异常.";
    }

    return $objects;


}

/**
 * 检查用户是否可以购买限购商品，如果可以，直接更新缓存
 * @param $uid
 * @param $product_discount_id
 * @param $amount
 * @return string
 */
function checkAndBuy($uid, $product_discount_id, $amount)
{

    //"pro_dis:{product_sales_id}:u:{user_id}" => limitation
    $key = "pro_dis:" . $product_discount_id . ":u:" . $uid;
    $cache = getRedisHandler();

    //search in the cache
    if(!$cache->get($key)){
        initLimitationFromDB($uid, $product_discount_id);
    }
//    $cachedLimitation = $cache->get($key);
//    $limitation = !$cachedLimitation ? initLimitationFromDB($uid, $product_discount_id) : $cachedLimitation;

    //refresh if can buy

    $leftnum = $cache->decrBy($key, $amount);
    // var_dump($leftnum);

    if ($leftnum < 0) {
        $cache->del($key);
    }
    return $leftnum;
}

/**
 * 重新生成用户限购缓存
 * @param $uid
 * @param $product_discount_id
 * @throws Exception
 */
function initLimitationFromDB($uid, $product_discount_id){
    // $product_discount_id = 2;
    $key = "pro_dis:" . $product_discount_id . ":u:" . $uid;
    $cache = getRedisHandler();

    //search in db
    $product_discount = M("product_discount")->find($product_discount_id);
    if ($product_discount == null) {
      return;
        // throw new Exception("ID为" . $product_discount_id . "的促销商品不存在");
    }

    $dao = M("order");
    $alreadyBought = $dao->join("order_product on order.order_id = order_product.order_id")->where(array(
        "order.user_id" => $uid,
        "order_product.product_discount_id" => $product_discount_id
    ))->field('sum(order_product.num) as sum')->select();
    // var_dump($dao);

    $limitation = $product_discount['xg_amount'] - 0 - ($alreadyBought[0]['sum'] - 0);
    $cache->set($key, $limitation, 3600);
    // var_dump($product_discount);

    // die();

    // return $limitation;
}

?>
